package log

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"irisfarm/app/helper"
	"os"
	"time"
)

func NewAppLog() {
	// 输出设备
	setOutput()

	// 输出格式
	setFormatter()

	// 日志等级
	setLevel()
}

func setOutput() {
	//创建输出日志文件
	logFilePath := "./storage/logs/app-" + time.Now().Format("2006-01-02") + ".txt"

	if !helper.FileExist("./storage/logs") {
		if err := os.MkdirAll("./storage/logs", 0777); err != nil {
			panic(err)
		}
	}

	// 使用os.O_RDWR|os.O_APPEND|os.O_CREATE这种形式既可以创建文件，又可以追加，不用再去判断文件是否存在
	logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)
	if err != nil {
		log.Fatal(err)
	}

	output := viper.GetString("log.output")
	if output == "file" {
		log.SetOutput(logFile)
	} else {
		log.SetOutput(os.Stdout)
	}
}

func setFormatter() {
	format := viper.GetString("log.format")
	if format == "json" {
		log.SetFormatter(&log.JSONFormatter{})
	} else {
		log.SetFormatter(&log.TextFormatter{})
	}
}

// log.Trace("Something very low level.")
// log.Debug("Useful debugging information.")
// log.Info("Something noteworthy happened!")
// log.Warn("You should probably take a look at this.")
// log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
// log.Fatal("Bye.")
// Calls panic() after logging
// log.Panic("I'm bailing.")
func setLevel() {
	level := viper.GetString("log.level")
	switch level {
	case "panic":
		log.SetLevel(log.PanicLevel)
	case "fatal":
		log.SetLevel(log.FatalLevel)
	case "error":
		log.SetLevel(log.ErrorLevel)
	case "warn":
		log.SetLevel(log.WarnLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "trace":
		log.SetLevel(log.TraceLevel)
	}
}
